package com.gzy.net_app.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import com.gzy.net_app.MainActivity;
import com.gzy.net_app.api.ApiService;
import com.gzy.net_app.application.AppContext;
import com.gzy.net_app.bean.ImageInfo;
import com.gzy.net_app.databinding.ActivityPublishBinding;
import com.gzy.net_app.ui.BaseActivity;
import com.gzy.network.NetworkApi;
import com.gzy.network.observer.BaseObserver;
import com.gzy.network.utils.KLog;
import com.orhanobut.hawk.Hawk;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PublishActivity extends BaseActivity<ActivityPublishBinding> {
  private static final int REQUEST_CODE = 10000;//权限
  private static final int TAKE_PHOTO = 11;// 拍照
  private static final int LOCAL_CROP = 13;// 本地图库

  public final String TAG = this.getClass().getSimpleName();

  String currentFileUrl = "";
  String publishItem = "";
  String publishText = "";


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //解决屏幕上衣
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    //android版本在6.0以上
    if (Build.VERSION.SDK_INT >= 23) {
      System.out.println("版本正确");
      checkPermission();
    } else {
      System.out.println("版本过低");
    }


    onListener();
  }

  private void onListener() {
    binding.tvPbQuxiao.setOnClickListener(view -> {
      binding.ivPbChoosePhoto.setVisibility(View.VISIBLE);
      binding.ivPbWancheng.setVisibility(View.GONE);
      binding.etPbLongtext.setText("");
      binding.tvPbSwitch.setText("私密");
      publishItem = "private";
      binding.stPbKaiguan.setChecked(false);
    });


    publishItem = "private";
    binding.btPbFabiao.setOnClickListener(view -> {
      publishText = binding.etPbLongtext.getText().toString().trim();
      if (publishText.isEmpty()) {
        AppContext.showToast("请输入文本");
        return;
      }
      addImageApi();
      // identifyFacePhoto();

    });

    binding.ivReturn.setOnClickListener(view -> finish());
    binding.ivPbChoosePhoto.setOnClickListener(view -> getPhoto());

    binding.stPbKaiguan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (b) {
          binding.tvPbSwitch.setText("公开");
          publishItem = "public";
        } else {
          binding.tvPbSwitch.setText("私密");
          publishItem = "private";
        }
      }
    });

    binding.ivPbWancheng.setOnClickListener(view -> getPhoto());
  }

  //获取人脸照片
  private void getPhoto() {
    CharSequence[] items = { "拍照", "图库" };// 裁剪items选项
    // 弹出对话框提示用户拍照或者是通过本地图库选择图片
    new AlertDialog.Builder(this)
        .setItems(items, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {

            switch (which) {
              // 选择了拍照
              case 0:
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, TAKE_PHOTO);
                break;
              // 调用系统图库
              case 1:
                // 创建Intent，用于打开手机本地图库选择图片
                Intent intent1 = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 启动intent打开本地图库
                startActivityForResult(intent1, LOCAL_CROP);
                break;
            }
          }
        }).show();
  }

  /**
   * 调用startActivityForResult方法启动一个intent后，
   * 可以在该方法中拿到返回的数据
   */
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
      case TAKE_PHOTO:// 拍照
        if (resultCode == RESULT_OK) {
          final Bitmap photo = data.getParcelableExtra("data");
          //将bitmap照片放入系统相册，并将照片给url
          currentFileUrl = AppContext.saveImageToGallery(this, photo);
          binding.ivPbWancheng.setVisibility(View.VISIBLE);
          binding.ivPbChoosePhoto.setVisibility(View.GONE);
          binding.ivPbWancheng.setImageBitmap(photo);
          Log.d(TAG, "onActivityResult: " + currentFileUrl);
        }
        break;
      case LOCAL_CROP:// 系统图库
        if (resultCode == RESULT_OK) {
          Uri uri = data.getData();
          binding.ivPbWancheng.setVisibility(View.VISIBLE);
          binding.ivPbChoosePhoto.setVisibility(View.GONE);
          binding.ivPbWancheng.setImageURI(uri);
          currentFileUrl = AppContext.getRealPathFromURI(this, uri);
          Log.d(TAG, "onActivityResult: " + currentFileUrl);
        }
        break;
    }
  }
  //权限
  private void checkPermission() {
    ActivityCompat.requestPermissions(PublishActivity.this,
        new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
        REQUEST_CODE);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode,
                                         String permissions[], int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
      //权限的申请结果返回
      case REQUEST_CODE: {
        if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          //已授权
          AppContext.showToast("授权成功");
        } else {
          //未授权
          AppContext.showToast("授权被拒绝");
        }
      }
    }
  }

  /**
   * 上传
   */
  private void addImageApi() {
    if (TextUtils.isEmpty(currentFileUrl)) {
      AppContext.showToast("请先选择照片哦");
      return;
    } else {
      showWaitDialog("上传中");
      File file = new File(currentFileUrl);
      MultipartBody.Part part = MultipartBody.Part.createFormData("image",
          file.getName(),
          RequestBody.create(MediaType.parse("image/*"),
              file));
      RequestBody tokenBody, loginBody, imageTextBody, publishStatusBody;

      tokenBody = RequestBody.create(MediaType.parse("text/plain"), "" + Hawk.get("token"));
      loginBody = RequestBody.create(MediaType.parse("text/plain"), "" + Hawk.get("username"));
      imageTextBody = RequestBody.create(MediaType.parse("text/plain"), "" + publishText);
      publishStatusBody = RequestBody.create(MediaType.parse("text/plain"), "" + publishItem);
      NetworkApi.createService(ApiService.class)
          .createOneImageInfoApi(part, tokenBody, loginBody, imageTextBody, publishStatusBody)
          .compose(NetworkApi.applySchedulers(new BaseObserver<ImageInfo>() {
            @Override public void onSuccess(ImageInfo imageInfo) {
              AppContext.showToast("上传成功");
              KLog.d(TAG, imageInfo.toString());
              hideWaitDialog();
              startActivity(new Intent(PublishActivity.this, MainActivity.class));
              finish();
            }

            @Override public void onFailure(Throwable e) {
              KLog.d(TAG, e.toString());
              AppContext.showToast("上传失败");
              hideWaitDialog();
            }
          }));
    }
  }

  @Override public void onBackPressed() {
    super.onBackPressed();
    finish();
  }
}